"""
FastAPI主应用
"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import os
from contextlib import asynccontextmanager
from loguru import logger

from app.core.config import settings
from app.databases.database import create_async_tables, close_db
from app.core.exceptions import AudioProcessingException
from app.api.v1 import health, audio

@asynccontextmanager
async def lifespan(app: FastAPI):
    # startup 部分
    os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
    os.makedirs("logs", exist_ok=True)
    try:
        import asyncio
        asyncio.create_task(create_async_tables())
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.exception(f"数据库表创建失败: {e}")
    yield
    # shutdown 部分
    logger.info("应用正在关闭...")
    await close_db()


# 创建FastAPI应用实例
app = FastAPI(
    title=settings.APP_NAME,
    description="提供音频升降调处理服务",
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(health.router, tags=["health"])
app.include_router(audio.router, prefix="/api/v1/audio", tags=["audio"])


@app.exception_handler(AudioProcessingException)
async def audio_processing_exception_handler(request: Request, exc: AudioProcessingException):
    """音频处理异常处理器"""
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": "AudioProcessingError", "message": exc.detail}
    )


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )
